<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="HTTP,性能优化,计算机网络," />










<meta name="description" content="前言前天飞猪电面的时候，面试我的那位师兄问了关于性能优化方面的问题，可能是由于有点紧张的缘故，答得不好，很多自己会的东西都没有说出来，而且回想起来我好像只说了个HTTP缓存，且HTTP缓存这块也没完全的说全，哎简直要哭晕在厕所里了。反思的时候想了想，这可能也是自己对这方面的知识虽然知道一些解决方案，但理解还是不够深刻的原因。没能做到提到这方面的问题就能从脑海里浮现出相应的一些解决方案。因此，先写篇">
<meta name="keywords" content="HTTP,性能优化,计算机网络">
<meta property="og:type" content="article">
<meta property="og:title" content="浅谈HTTP缓存">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/08/16/浅谈HTTP缓存/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="前言前天飞猪电面的时候，面试我的那位师兄问了关于性能优化方面的问题，可能是由于有点紧张的缘故，答得不好，很多自己会的东西都没有说出来，而且回想起来我好像只说了个HTTP缓存，且HTTP缓存这块也没完全的说全，哎简直要哭晕在厕所里了。反思的时候想了想，这可能也是自己对这方面的知识虽然知道一些解决方案，但理解还是不够深刻的原因。没能做到提到这方面的问题就能从脑海里浮现出相应的一些解决方案。因此，先写篇">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://images.gitee.com/uploads/images/2018/0802/202340_bbea7d99_1575229.png">
<meta property="og:image" content="https://images.gitee.com/uploads/images/2018/0816/113410_ac217adc_1575229.png">
<meta property="og:image" content="http://juanha.coding.me/2017/03/05/http-cache/http-cache.png">
<meta property="og:image" content="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/images/http-cache-decision-tree.png">
<meta property="og:updated_time" content="2018-08-16T14:36:34.937Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浅谈HTTP缓存">
<meta name="twitter:description" content="前言前天飞猪电面的时候，面试我的那位师兄问了关于性能优化方面的问题，可能是由于有点紧张的缘故，答得不好，很多自己会的东西都没有说出来，而且回想起来我好像只说了个HTTP缓存，且HTTP缓存这块也没完全的说全，哎简直要哭晕在厕所里了。反思的时候想了想，这可能也是自己对这方面的知识虽然知道一些解决方案，但理解还是不够深刻的原因。没能做到提到这方面的问题就能从脑海里浮现出相应的一些解决方案。因此，先写篇">
<meta name="twitter:image" content="https://images.gitee.com/uploads/images/2018/0802/202340_bbea7d99_1575229.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/08/16/浅谈HTTP缓存/"/>





  <title>浅谈HTTP缓存 | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/08/16/浅谈HTTP缓存/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">浅谈HTTP缓存</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-16T12:21:28+08:00">
                2018-08-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/性能优化/" itemprop="url" rel="index">
                    <span itemprop="name">性能优化</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,640
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>前天飞猪电面的时候，面试我的那位师兄问了关于性能优化方面的问题，可能是由于有点紧张的缘故，答得不好，很多自己会的东西都没有说出来，而且回想起来我好像只说了个HTTP缓存，且HTTP缓存这块也没完全的说全，哎简直要哭晕在厕所里了。反思的时候想了想，这可能也是自己对这方面的知识虽然知道一些解决方案，但理解还是不够深刻的原因。没能做到提到这方面的问题就能从脑海里浮现出相应的一些解决方案。因此，先写篇关于HTTP缓存文章吧，梳理一下关于HTTP缓存上自己的一些理解。</p>
<h3 id="一、HTTP缓存概述（HTTP-Cache）"><a href="#一、HTTP缓存概述（HTTP-Cache）" class="headerlink" title="一、HTTP缓存概述（HTTP Cache）"></a>一、HTTP缓存概述（HTTP Cache）</h3><p>要搞清楚HTTP缓存，首先当然是要搞清楚缓存是啥，按照MDN的描述，缓存是这样的：</p>
<blockquote>
<p>缓存是一种保存资源副本并在下次请求时直接使用该副本的技术。当 web 缓存发现请求的资源已经被存储，它会拦截请求，返回该资源的拷贝，而不会去源服务器重新下载。这样带来的好处有：缓解服务器端压力，提升性能(获取资源的耗时更短了)。对于网站来说，缓存是达到高性能的重要组成部分。缓存需要合理配置，因为并不是所有资源都是永久不变的：重要的是对一个资源的缓存应截止到其下一次发生改变（即不能缓存过期的资源）。</p>
</blockquote>
<p>上面已经将会缓存是什么描述的很清楚了，而HTTP缓存顾名思义，就是通过HTTP协议，来实现对资源缓存的目的。总的来说，HTTP缓存主要通过两个HTTP头来实现的，其中Expires是由HTTP1.0提供的，而Cache-Control则是由HTTP1.1所提供的：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0802/202340_bbea7d99_1575229.png" alt="HTTP缓存图1.PNG"></p>
<p>下面我们就来对这两个头进行一个了解。</p>
<h3 id="二、Expires"><a href="#二、Expires" class="headerlink" title="二、Expires"></a>二、Expires</h3><p>Expires是由HTTP1.0所提供的支持HTTP缓存的头部，由服务器返回，用GMT格式的字符串表示：</p>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">expires</span>: Tue, 14 Aug 2018 14:32:49 GMT</span><br></pre></td></tr></table></figure>
<p>而读取缓存的条件则是：缓存过期时间（服务器的时间）&lt; 当前时间（客户端的时间）</p>
<p>值得注意的是，我们在expires所设置的时间是一个绝对的时间，而且所参照的是用户电脑上所设置的时间。这种绝对的时间很容易出问题，当用户本地的时间不准确，或用户进行跨时区的移动时，这个时间很可能就会过期，而无法发挥它本应该发挥的作用。</p>
<p>其次，在HTTP1.0里，没有提供相应的配置缓存的方法，只是提供了这个强缓存的头部而已，不足以满足项目对缓存多样化的需求。也正是出于以上两个原因，在HTTP1.1中对HTTP缓存又进行了升级。</p>
<h3 id="三、-Cache-Control"><a href="#三、-Cache-Control" class="headerlink" title="三、 Cache-Control"></a>三、 Cache-Control</h3><p>正是由于Expires存在着很多不足，所以HTTP1.1又为我们提供了 </p>
<p>Cache-Control主要可配置的参数有以下几个：</p>
<ol>
<li>max-age 会指定从请求的时间开始，允许获取的响应被重用的最长时间（单位：秒）。例如，“max-age=60”表示可在接下来的 60 秒缓存和重用响应。</li>
<li>Public 表示响应可被任何缓存区缓存</li>
<li>Private 表示对于单个用户的整个或部分响应消息，不能被共享缓存处理。这些响应通常只为单个用户缓存，因此不允许任何中间缓存对其进行缓存。例如，用户的浏览器可以缓存包含用户私人信息的 HTML 网页，但 CDN 却不能缓存。</li>
<li>no-cache 表示必须先与服务器确认返回的响应是否发生了变化，然后才能使用该响应来满足后续对同一网址的请求。因此，如果存在合适的验证，no-cache 会发起往返通信来验证缓存的响应，但如果资源未发生变化，则可避免下载。</li>
<li>no-store则要简单得多。它直接禁止浏览器以及所有中间缓存存储任何版本的返回响应，例如，包含个人隐私数据或银行业务数据的响应。每次用户请求该资产时，都会向服务器发送请求，并下载完整的响应。</li>
<li>min-fresh 表示客户端可以接收响应时间小于当前时间加上指定时间的响应。（用的不多）</li>
<li>max-stale 表示客户端可以接收超出超时期间的响应消息。如果指定max-stale消息的值，那么客户机可以接收超出超时期指定值之内的响应消息。（用的不多）</li>
</ol>
<h3 id="四、强缓存"><a href="#四、强缓存" class="headerlink" title="四、强缓存"></a>四、强缓存</h3><p>上面已经将Catch-Control做了一个简单的介绍，而具体使用它们二者进行缓存操作的具体实现又分为强缓存与协商缓存。首先来聊一聊强缓存。</p>
<p>强缓存是利用Expires或者Cache-Control这两个http response header实现的，它们都用来表示资源在客户端缓存的有效期。在这个有效期内当浏览器对某个资源的请求命中了强缓存时，其返回的http状态为200，并且不会去对服务器进行请求，而是直接使用其本地的缓存。</p>
<p>具体实现如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">expires: Tue, 21 Aug 2018 10:17:45 GMT</span><br><span class="line">cache-control: max-age=691200</span><br></pre></td></tr></table></figure>
<p>只要存在以上两个头部信息的其中一个，我们就可以对资源进行强缓存了。另外需要注意的是，当Catch-Control的优先级是要高于expires的。</p>
<p>总的来说，强缓存是前端性能优化的一大助力。当我们页面存在很多长期不变的静态资源时，都应该对其进行强缓存的处理，我们通常可以为这些静态资源全部配置一个超时时间很长的Expires或Cache-Control。当用户在访问网页时，就只会在第一次加载时从服务器请求静态资源，在往后访问该页面时，就只要缓存没有失效并且用户没有强制刷新的条件下都会从自己的缓存中加载。这样既节省了资源加载的时间的消耗，又不会去访问服务器，可以有效地为服务器减压。</p>
<p>不过强缓存也存在一个很大的弊端，那就是对于动态资源它就有点力不从心了。因为如果我们对动态资源进行了强缓存，那么很可能会在这动态资源更改后，浏览器还是会直接去请求没有更改前的动态资源。也这是由于这方面的考虑，在强缓存外还存在着协商缓存的缓存方案。</p>
<h3 id="五、协商缓存"><a href="#五、协商缓存" class="headerlink" title="五、协商缓存"></a>五、协商缓存</h3><p>当浏览器对某个资源的请求没有命中强缓存，就会发一个请求到服务器，验证协商缓存是否命中，如果协商缓存命中，请求响应返回的http状态为304并且会显示一个Not Modified的字符串；<br>若未命中请求，则将资源返回客户端，并更新本地缓存数据，并返回200的状态码。</p>
<p>除此之外，我们也可以设置为协商缓存，以解决动态资源缓存与更新的问题，首先我们来看一张关于协商缓存的图：</p>
<p><img src="https://images.gitee.com/uploads/images/2018/0816/113410_ac217adc_1575229.png" alt="输入图片说明"></p>
<p>可以看到，在这个实现了协商缓存的Cache-Control中，设置了no-catch，当我们设置为no-catch时，我们就是可以直接去访问服务器，去查看该资源的更改情况，已确定是是否需要使用缓存。而在校验的这一步我们就需要使用以下几个头来帮助验证资源的更改情况了：</p>
<ul>
<li>Last-Modified：表示这个响应资源的最后修改时间。web服务器在响应请求时，会告诉浏览器该资源的最后修改时间，但它的最小单位是秒级，也就是如果我们在1秒内多次修改该资源，那么Last-Modified也无法发挥其应有的作用。</li>
<li>If-Modified-Since：当资源过期时（强缓存失效），发现资源具有Last-Modified声明，则再次向web服务器请求时带上头 If-Modified-Since，表示请求时间。web服务器收到请求后发现有头If-Modified-Since 则与被请求资源的最后修改时间进行比对。若最后修改时间较新，说明资源又被改动过，则响应整片资源内容（写在响应消息包体内），HTTP 200；若最后修改时间较旧，说明资源无新修改，则响应HTTP 304 (无需包体，节省浏览)，告知浏览器继续使用所保存的cache。</li>
</ul>
<p>也正是由于 Last-Modified存在着缺陷，我们就需要ETag来帮助我们来对资源的更改进行判断：</p>
<ul>
<li>Etag：当Web服务器响应请求时，会告诉浏览器当前资源在服务器的唯一标识（生成规则是由服务器决定的）。就比如在Apache中，ETag的值，其默认是对文件的索引节（INode），大小（Size）和最后修改时间（MTime）进行Hash后得到的。</li>
<li>If-None-Match：当资源过期时，如果发现资源具有Etage声明，则再次向web服务器请求时带上头If-None-Match （Etag的值）。Web服务器收到请求后发现有头If-None-Match， 就会将其被请求的资源的相应校验字段进行对比，然后再决定返回200或304。</li>
</ul>
<p>这就是强缓存与协商缓存的大部分情况了，具体的流程可见下图：</p>
<p><img src="http://juanha.coding.me/2017/03/05/http-cache/http-cache.png" alt="image"></p>
<p>原图链接：<a href="http://juanha.coding.me/2017/03/05/http-cache/http-cache.png" target="_blank" rel="noopener">http://juanha.coding.me/2017/03/05/http-cache/http-cache.png</a></p>
<h4 id="六、定义最佳-Cache-Control-策略"><a href="#六、定义最佳-Cache-Control-策略" class="headerlink" title="六、定义最佳 Cache-Control 策略"></a>六、定义最佳 Cache-Control 策略</h4><p><img src="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/images/http-cache-decision-tree.png" alt="image"></p>
<p>通常我们可以按照上面这张流程图来对HTTP缓存进行相应的配置，详情可以看这篇文章：</p>
<blockquote>
<p><a href="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching" target="_blank" rel="noopener">https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching</a>?</p>
</blockquote>
<p>这位大佬对缓存的配置做了一个很好的阐述。</p>
<p>参考资料：</p>
<ul>
<li><a href="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching" target="_blank" rel="noopener">https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching</a>?</li>
<li><a href="https://www.cnblogs.com/lyzg/p/5125934.html#_label3" target="_blank" rel="noopener">https://www.cnblogs.com/lyzg/p/5125934.html#_label3</a></li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching_FAQ" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching_FAQ</a></li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/HTTP/" rel="tag"># HTTP</a>
          
            <a href="/blog/tags/性能优化/" rel="tag"># 性能优化</a>
          
            <a href="/blog/tags/计算机网络/" rel="tag"># 计算机网络</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/08/ECMAScipt5.1文档阅读笔记——Object类型/" rel="next" title="ECMAScript5.1文档阅读笔记——Object类型">
                <i class="fa fa-chevron-left"></i> ECMAScript5.1文档阅读笔记——Object类型
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/09/06/深入浅出事件循环机制/" rel="prev" title="深入浅出事件循环机制">
                深入浅出事件循环机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一、HTTP缓存概述（HTTP-Cache）"><span class="nav-number">2.</span> <span class="nav-text">一、HTTP缓存概述（HTTP Cache）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、Expires"><span class="nav-number">3.</span> <span class="nav-text">二、Expires</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、-Cache-Control"><span class="nav-number">4.</span> <span class="nav-text">三、 Cache-Control</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四、强缓存"><span class="nav-number">5.</span> <span class="nav-text">四、强缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五、协商缓存"><span class="nav-number">6.</span> <span class="nav-text">五、协商缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#六、定义最佳-Cache-Control-策略"><span class="nav-number">6.1.</span> <span class="nav-text">六、定义最佳 Cache-Control 策略</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
